<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'device:management:inDeviceManagement:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
    destroyOnClose={true}
     @close="handleDrawerClose"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" ref="formRef" :key="formTimeKey" />
    <div class="fireVeIm">
      <div class="fireImg">
        <span>
          示例图:
        </span>
        <Image v-if="imageFire" :src="imageFire" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" style="width: 150px;height:auto;" alt="">
      </div>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsDeviceManagementInDeviceManagementForm">
  import { ref, unref, computed,defineEmits,watch } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { InDeviceManagement, inDeviceManagementSave, inDeviceManagementForm,inDeviceManagementListData } from '/@/api/device.management/inDeviceManagement';
  import {Office, officeTreeData,officeListData,officeTreeDataList} from '/@/api/sys/office';
  import {unitRegionListData} from '/@/api/unitmanage/unitRegion';
  import {unitBuildingListData} from '/@/api/unitmanage/unitBuilding';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { inEquipmentTypeListData } from '/@/api/device.management/inEquipmentType';
  import { Image } from 'ant-design-vue';
  import { inFireHostListData } from '/@/api/device.management/inFireHost';




  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('device.management.inDeviceManagement');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<InDeviceManagement>({} as InDeviceManagement);
  const imageFire=ref()
  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增') : t('编辑'),
  }));

  const ResEnterpriseId=ref<any>()

  const hostEquipmentName=ref('')
  const hostParams = computed(() => {
    return {
      equipmentName: hostEquipmentName.value,
    };
  })

  const EnterpriseParams = ref<Recordable>({
     name:''
    });

 const MaintenanceMethod=ref('')
 const MaintenanceMethodCode=ref('')
  
const buildingName=ref('')

// 使用 computed 动态计算 params 对象
const selectParams = computed(() => {
  return {
    name: buildingName.value,
    unitCode:EnterpriseId.value? EnterpriseId.value : ResEnterpriseId.value,
  };
});

const EquipmentName=ref('')
const EquipmentTypeParams=computed(() => {
  return {
   equipmentName:EquipmentName.value
  };
});


const RegionName=ref('')
const EnterpriseId=ref<any>()

const RegionParams = computed(() => {
  console.log('RegionName', EnterpriseId.value)
  return {
    name: RegionName.value,
    enterpriseId:EnterpriseId.value? EnterpriseId.value:ResEnterpriseId.value,
  };
});

  const inputFormSchemas: FormSchema[] = [   
    {
      label: t('设备名称'),
      field: 'equipmentName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    {
      label: t('设备编码'),
      field: 'equipmentCode',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    // {
    //   label: t('设备类型id'),
    //   field: 'equipmentTypeId',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 255,
    //   },
    //   required: true,
    // },
    {
      label: t('设备类型'),
      field: 'equipmentTypeId',
      fieldLabel:'equipmentType',
      component: 'Select',
      componentProps:{
              api: inEquipmentTypeListData,
              params: EquipmentTypeParams,
              fieldNames:{
                  label:'equipmentName',
                  value:'equipmentCode'
                },
              resultField: 'list',
              notFoundContent: '未查询到记录',
              filterTreeNode: false,
              filterOption: false,
              allowClear: true,
              immediate: true,
              onSearch: (value: string) => {
                EquipmentName.value = value;
                console.log('输入的值:', value)
              },
              onSelect:async(value)=>{
              const data={}
              data.equipmentCode=value.key
              const res= await inEquipmentTypeListData(data)
              console.log('选择的设备类型:',value)
              console.log('选择的设备类型:',res)
              MaintenanceMethod.value=res.list[0].maintenanceMethod
              MaintenanceMethodCode.value=res.list[0].maintenanceMethodCode
          }
      },
      required: true,
    },
    {
      label: t('所属主机'),
      field: 'hostId',
      component: 'Input',
      required: true,
    },
    {
      label: t('企业名称'),
      field: 'enterpriseId',
      fieldLabel:'enterpriseName',
      component: 'Select',
      componentProps: () => {
        return {
          placeholder: t('请输入主体名称'),
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          allowClear: true,
          filterTreeNode: false,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
          onChange: (unitCode)=>{
            EnterpriseId.value=unitCode
            console.log('选择的企业:',unitCode)
          }
        };
      },
      required: true,
    },
    {
      label: t('安装建筑名称'),
      field: 'buildId',
      fieldLabel:'buildName',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api: unitBuildingListData,
          params:selectParams,
          resultField:'list',
          fieldNames: { label: 'name', value: 'id' },    
          allowClear:true,
          immediate:false,
          each:false,
          showSelect:true,
          optionFilterProp: 'label',
          showSearch:true,
          onSearch: (value) => {
          buildingName.value = value;
          // console.log('输入的值:', value);
        },
      },
      // required: true,
    },
    {
      label: t('区域名称'),
      field: 'regionId',
      fieldLabel:'regionName',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        api:unitRegionListData,
        params:RegionParams,
        resultField:'list',
          fieldNames: { label: 'name', value: 'id' },    
          allowClear:true,
          immediate:false,
          each:false,
          showSelect:true,
          optionFilterProp: 'label',
          showSearch:true,
          onSearch: (value) => {
          RegionName.value = value;
          console.log('输入的值:', RegionName.value);
        },
      },
      // required: true,
    },
    {
      label: t('详细地址'),
      field: 'address',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    {
      label: t('当前设备实时状态'),
      field: 'realStatus',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled:true,
      },
    },
    {
      label: t('示例图'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        fileUrl:computed(() => record.value.fileUrl),
        bizType: 'inDeviceManagement_file',
        uploadType: 'all',
        maxNumber:1,
      },
    },
    {
      label: t('防火分区'),
      field: 'firePartition',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await inDeviceManagementForm(data);
    console.log('res', res);
    ResEnterpriseId.value=res.inDeviceManagement.enterpriseId
    imageFire.value=res.inDeviceManagement.image
    record.value = (res.inDeviceManagement || {}) as InDeviceManagement;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });
  
  const formRef = ref<any>();
 const formTimeKey=ref(Date.now());
const handleDrawerClose = () => {
  formRef.value.resetFields();
  EnterpriseId.value=undefined;
}

  async function handleSubmit() {
    try {
      let data = await validate();
      data={
        ...data,
        status:0,
        maintenanceMethod:MaintenanceMethod.value,
        maintenanceMethodCode:MaintenanceMethodCode.value,
        image:(data.dataMap.inDeviceManagement_fileUrl != null) ? (data.dataMap.inDeviceManagement_fileUrl.split('?')[0]) : record.value.image
      }
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };
      // console.log('submit', params, data, record);
      const res = await inDeviceManagementSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped lang="less"> 
.fireVeIm{
  display: flex;
  justify-content: space-start;
  align-items: center;
  margin-bottom: 5%;
  margin-left: 5%;
}
.fireImg {
  width: 20%;
  height: 200px;
}
</style>